package pl.umk.mat.fred.unicore.urc.storagemanagement.tree.sorters;

import java.util.Calendar;

import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerSorter;

import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.CatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.FileNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.GridNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.MultiplyCatalogNode;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.Node;

public class LastModifiedSorter extends ViewerSorter {
	
	private int direction = -1; // DESCENTING
	
	public int compare(Viewer viewer, Object e1, Object e2) {
		int tmp = getType(e1) - getType(e2); 
		if (tmp == 0) {
			Calendar c1 = getLastModified((Node)e1);
			Calendar c2 = getLastModified((Node)e2);
			return (c1 == null || c2 == null) ? 0 : c1.compareTo(c2) * direction;
		}
		return tmp;
	}
	
	private int getType(Object e) {
		if (e instanceof FileNode) {
			return 2;
		}
		if ((e instanceof CatalogNode) && (e instanceof MultiplyCatalogNode)) {
			return 1;
		}
		if (e instanceof GridNode) {
			return 0;
		}
		return -1;
	}
	
	private Calendar getLastModified(Node n) {
		if (n instanceof FileNode) {
			return ((FileNode)n).getLastModified();
		} else if (n instanceof CatalogNode) {
			return ((CatalogNode)n).getLastModified();
		}
		return null;
	}
}
